package com.snake.springboot.custom.config;

import com.aliyun.oss.ServiceException;
import com.snake.springboot.custom.api.exception.LoginExpiresException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.snake.alert.event.ExceptionEvent;
import org.snake.common.exception.IllegalStringException;
import org.snake.common.exception.LoginException;
import org.snake.common.exception.OperationException;
import org.snake.common.result.ResponseResult;
import org.snake.common.result.ResponseResultFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 *全局异常处理
 * @author YANG
 */
@Component
@RestControllerAdvice
public class ExceptionAdviceHandler {
    private static final Logger logger = LoggerFactory.getLogger(ExceptionAdviceHandler.class);
    private ApplicationContext applicationContext;
    @Autowired
    public ExceptionAdviceHandler(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @ExceptionHandler(ServiceException.class)
    public ResponseResult<Object> serviceException(ServiceException e) {
        logger.error("业务异常：{}" ,e.getMessage());
        return ResponseResultFactory.error(e.getMessage());
    }
    @ExceptionHandler(OperationException.class)
    public ResponseResult<Object> operationException(OperationException e) {
        logger.error("业务异常：{}" ,e.getMessage());
        return ResponseResultFactory.error(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public ResponseResult<Object> exception(Exception e) {
        logger.error("程序出错：" ,e);
        String msg = e.getMessage()==null?e.toString():e.getMessage();
        applicationContext.publishEvent(new ExceptionEvent(this, e));
        return ResponseResultFactory.error(msg);
    }

    @ExceptionHandler(LoginException.class)
    public ResponseResult<Object> loginException(LoginException e) {
        logger.error("登录异常：{}" ,e.getMessage());
        return ResponseResultFactory.error(e.getMessage());
    }

    @ExceptionHandler(LoginExpiresException.class)
    public ResponseResult<Object> loginExpiresException(LoginExpiresException e) {
        logger.error("登录超时异常：{}" ,e.getMessage());
        return ResponseResultFactory.expire(e.getMessage(),"");
    }

    @ExceptionHandler(IllegalStringException.class)
    public ResponseResult<Object> illegalStringException(IllegalStringException e) {
        logger.error("非法字符串异常：{}" ,e.getMessage());
        return ResponseResultFactory.error(e.getMessage());
    }

}
